import Vue from 'vue';
import VueRouter from 'vue-router';
import LoginPlatfrom from '../views/login/LoginPlatform.vue';
import RegisterPlatform from '../views/login/RegisterPlatform.vue';
import ChangePwd from '../views/login/ChangePwd.vue';
import HomePage from '../views/home/HomePage.vue'

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'LoginPlatfrom',
        component: LoginPlatfrom
    },
    {
        path: '/register',
        name: 'RegisterPlatform',
        component: RegisterPlatform
    },
    {
        path: '/changePwd',
        name: 'ChangePwd',
        component: ChangePwd
    },
    {
        path: '/home',
        name: HomePage,
        component: HomePage,
        meta: {
            requireAuth: true
        }
    }
];

const router = new VueRouter({
    mode: 'history',
    // base: process.env.BASE_URL,
    routes
});

// 注册全局前置守卫，每次路由跳转前执行
router.beforeEach((to, from, next) => {
    // 检查目标路由中是否有需要身份验证的路由记录
    if (to.matched.some(record => record.meta.requiresAuth)) {
        // 获取Vuex store 实例
        const store = Vue.prototype.$store;
        // 如果用户没有登录 则跳转登录页面
        if (!store.state.user) {
            next({ path: '/login' });
        } else {
            // 否则放行 
            next();
        }
    } else {
        // 直接放行
        next();
    }
});

export default router;